package com.ctshk.rpc.order.season.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.enums.Currency;
import com.ctshk.common.enums.IsDeletedCode;
import com.ctshk.common.enums.ProductType;
import com.ctshk.common.enums.SystemBusinessType;
import com.ctshk.common.model.TokenUser;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.common.utils.SnowflakeIdWorker;
import com.ctshk.rpc.booking.enums.SupplierReserveTypeEnum;
import com.ctshk.rpc.booking.req.system.ship.add.SupplierOrderSystemShipAddReq;
import com.ctshk.rpc.booking.req.system.ship.add.SupplierSystemOrderShipAddReq;
import com.ctshk.rpc.booking.req.system.ship.add.SupplierSystemOrderShipTicketAddReq;
import com.ctshk.rpc.booking.service.ISupplierOrderService;
import com.ctshk.rpc.order.season.dto.SeasonOrderPayDTO;
import com.ctshk.rpc.order.season.dto.SeasonOrderTouristDataDTO;
import com.ctshk.rpc.order.season.dto.SeasonProductOrderShipDTO;
import com.ctshk.rpc.order.season.entity.SeasonOrder;
import com.ctshk.rpc.order.season.entity.SeasonProductOrderShip;
import com.ctshk.rpc.order.season.mapper.SeasonOrderMapper;
import com.ctshk.rpc.order.season.mapper.SeasonProductOrderShipMapper;
import com.ctshk.rpc.order.season.service.ISeasonOrderTouristService;
import com.ctshk.rpc.order.season.service.ISeasonProductOrderShipService;
import com.ctshk.rpc.order.ship.service.IShipOrderService;
import com.ctshk.rpc.system.dto.UserDTO;
import com.ctshk.rpc.system.service.ISysUserService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * <p>
 * 套票-订单-船票订单 服务实现类
 * </p>
 *
 * @author 杨林
 * @since 2021-03-24
 */
@DubboService
public class SeasonProductOrderShipServiceImpl extends ServiceImpl<SeasonProductOrderShipMapper, SeasonProductOrderShip> implements ISeasonProductOrderShipService {
     @Autowired
     private SeasonProductOrderShipMapper orderShipMapper;

    @Autowired
    private SeasonOrderMapper seasonOrderMapper;
    @Autowired
    private ISeasonOrderTouristService seasonOrderTouristService;

    @DubboReference
    private ISupplierOrderService supplierOrderService;

    @DubboReference
    private ISysUserService iSysUserService;
    @DubboReference
    private IShipOrderService shipOrderService;

    /* @MethodName: 保存船票订单信息
     * @Description: TODO
     * @Param:
     * @Return:
     * @Author: 杨林
     * @Date:2021/3/25 9:36
     **/
    @Override
    public void saveShipProduct(List<SeasonProductOrderShipDTO> shipList, Long userId, Long orderId) {
        LocalDateTime now=LocalDateTime.now();
        List<SeasonProductOrderShip> list=shipList.stream().map(
                shipReq->{
                    SeasonProductOrderShip ship= EntityUtil.copy(shipReq,SeasonProductOrderShip.class);
                    ship.setCreateId(userId);
                    ship.setGmtCreate(now);
                    ship.setIsDeleted(IsDeletedCode.NO.getCode());
                    ship.setSeasonOrderId(orderId);
                    ship.setId(SnowflakeIdWorker.nextId());
                    return ship;
                }
        ).collect(Collectors.toList());

        orderShipMapper.insertBatchSomeColumn(list);
    }

    /* @MethodName: 获取船票订单信息
     * @Description: TODO
     * @Param:
     * @Return:
     * @Author: 杨林
     * @Date:2021/3/30 16:42
     **/
    @Override
    public List<SeasonProductOrderShipDTO> getOrderShipList(Long id) {
        List<SeasonProductOrderShipDTO> resultList=EntityUtil.copyList(
                orderShipMapper.selectList(
                        new QueryWrapper<SeasonProductOrderShip>().lambda()
                                .eq(SeasonProductOrderShip::getSeasonOrderId,id)
                                .eq(SeasonProductOrderShip::getIsDeleted,IsDeletedCode.NO.getCode())

                ), SeasonProductOrderShipDTO.class);

        return resultList;


    }


    /* @MethodName: 船票下供应商 预订单
     * @Description: TODO
     * @Param:
     * @Return:
     * @Author: 杨林
     * @Date:2021/4/7 17:12
     **/
    @Override
    public void playSupplierOrder(Long orderId, TokenUser tokenUser) {
        SeasonOrder  seasonOrder=getSeasonOrderById(orderId);
        //旅客信息
        List<SeasonOrderTouristDataDTO> touristList= seasonOrderTouristService.getTouristList(orderId);
        //是否是同一供应商（判读条件 主订单的 供应商id(就是负责人的部门id) 是否与机票一直）
        boolean ifEqualSupplier=true;
        //获取当前用户信息
        UserDTO user = iSysUserService.getUser(new UserDTO().setId(tokenUser.getId()));
        UserDTO chargeDto=iSysUserService.getUser(new UserDTO().setId(seasonOrder.getChargeUserId()));
        Long deptId=chargeDto.getDeptId();
        List<SeasonProductOrderShipDTO>  shipList=getOrderShipList(orderId);
        if(!CollectionUtils.isEmpty(shipList)){
            SeasonProductOrderShipDTO shipDto1=shipList.get(0);
            if(!shipDto1.getSupplierId().equals(deptId)){
                ifEqualSupplier=false;
            }
            playSupplierShipOrder(seasonOrder,touristList,shipList,shipDto1.getSupplierId(),shipDto1.getSupplierName(),user);
            if(!ifEqualSupplier){//不是同一供应商 再次发起供应商预订单 只是供应商id 不同
                String depName=chargeDto.getDept();
                playSupplierShipOrder(seasonOrder,touristList,shipList,deptId,depName,user);
            }
        }
    }

    /* @MethodName: 下船票的 供应商预订单
     * @Description: TODO
     * @Param: 
     * @Return: 
     * @Author: 杨林
     * @Date:2021/4/12 15:43
    **/
    private void playSupplierShipOrder(SeasonOrder seasonOrder, List<SeasonOrderTouristDataDTO> touristList, List<SeasonProductOrderShipDTO> shipList, Long supplierId, String supplierName, UserDTO user) {
        SupplierOrderSystemShipAddReq shipAddReq=new SupplierOrderSystemShipAddReq();
        SeasonProductOrderShipDTO shipDto1=shipList.get(0);
        //订单类型
        shipAddReq.setOrderType(1);
        //供应商ID不能为空
        shipAddReq.setSupplierId(supplierId);
        //供应商名称
        shipAddReq.setSupplierName(supplierName);
        //供应商订单类型不能为空 1:普通订单,2:内部挂账订单
        shipAddReq.setSupplierOrderType("2");
        //供应商销售编号/部门ID(根据'供应商订单编号'显示，1：供应商销售编号，2：部门ID)
        shipAddReq.setOriginalSaleNumber(String.valueOf(user.getDeptId()));
        //业务类型不能为空
        shipAddReq.setBusinessType(SystemBusinessType.SHIP_TICKET.getCode());
        //预订类型
        shipAddReq.setReserveTypeId(SupplierReserveTypeEnum.SHIP.getId());
        //产品类型
        shipAddReq.setProductType(ProductType.MANUAL_ENTRY.getCode());
        //资源所属部门ID
        shipAddReq.setDepartmentId(user.getDeptId());
        //资源所属部门
        shipAddReq.setDepartment(user.getDept());
        //销售单号
        shipAddReq.setSaleNumber(seasonOrder.getOrderNumber());
        //产品编号(通用)
        shipAddReq.setProductNumber(String.valueOf(shipDto1.getProductId()));
        //产品名称
        shipAddReq.setProductNumber(seasonOrder.getProductName());
        //总金额
        shipAddReq.setTotalFee(seasonOrder.getOrderAmount());
        //币种id
        shipAddReq.setCurrencyId(Currency.HKD.getCode());
        //币种
        shipAddReq.setCurrency(Currency.HKD.getCurrency());
        //应付金额不能为空
        shipAddReq.setPayableAmount(seasonOrder.getReceivableAmount());
        //付款类型ID不能为空
        //hotelReq.setPayTypeId();
        SupplierSystemOrderShipAddReq shipReq=new SupplierSystemOrderShipAddReq();
        shipReq.setOrderId(seasonOrder.getId());
        shipReq.setSuitablePeople(shipDto1.getSupplierName());
        // shipReq.setSeatJson(shipDto.getCabinClass);

        List<SupplierSystemOrderShipTicketAddReq>  sysList=new LinkedList<>();
        for(SeasonProductOrderShipDTO shipDto:shipList){
            for(SeasonOrderTouristDataDTO dataDto:touristList){
                SupplierSystemOrderShipTicketAddReq touristAddReq=new SupplierSystemOrderShipTicketAddReq();
                touristAddReq.setTouristId(dataDto.getId());
                touristAddReq.setTouristName(dataDto.getTouristName());
                touristAddReq.setTouristTypeId(dataDto.getTouristTypeId());
                touristAddReq.setTouristType(dataDto.getTouristType());
                touristAddReq.setOrderId(seasonOrder.getId());
                touristAddReq.setShipId(shipDto.getProductId());
                //touristAddReq.setTravelType(shipDto.getTripType());
                touristAddReq.setGoLocationJson(shipDto.getDepCityName());
                touristAddReq.setDesLocationJson(shipDto.getArrCityName());
                touristAddReq.setBusNumber(shipDto.getVoyage());
                touristAddReq.setStartTime(shipDto.getDepTime());
                sysList.add(touristAddReq);
            }
        }
        shipReq.setSupplierSystemOrderShipTicketAddReqList(sysList);
        shipAddReq.setSupplierSystemOrderShipAddReq(shipReq);
        supplierOrderService.addSystemShip(shipAddReq,user.getId());
    }

    /* @MethodName: 动态套票 下各自订单后 确认对应状态
     * @Description: TODO
     * @Param:
     * @Return:
     * @Author: 杨林
     * @Date:2021/4/14 10:57
     **/
    @Override
    public void changeAffirmState(Long orderId, Integer isAffirm) {
        UpdateWrapper<SeasonProductOrderShip> updateWrapper=new UpdateWrapper<>();
        updateWrapper.lambda().eq(SeasonProductOrderShip::getOrderId,orderId);
        updateWrapper.lambda().set(SeasonProductOrderShip::getScheduledStatus,isAffirm);
        orderShipMapper.update(null,updateWrapper);
    }

    /* @MethodName: 退款状态
     * @Description: TODO
     * @Param:
     * @Return:
     * @Author: 杨林
     * @Date:2021/4/20 10:25
     **/
    @Override
    public void changeCancelOrderState(Long orderId, Integer cancelStatus) {
        UpdateWrapper<SeasonProductOrderShip> updateWrapper=new UpdateWrapper<>();
        updateWrapper.lambda().eq(SeasonProductOrderShip::getOrderId,orderId);
        updateWrapper.lambda().set(SeasonProductOrderShip::getCancelStatus,cancelStatus);
        orderShipMapper.update(null,updateWrapper);
    }

    /* @MethodName: 固定套票 下船票订单 走内部挂账
     * @Description: TODO
     * @Param: 
     * @Return: 
     * @Author: 杨林
     * @Date:2021/4/21 14:08
    **/
    @Override
    public void playInternalOrder(Long orderId, TokenUser user) {

    }

    /* @MethodName: 下船片订单接口
     * @Description: TODO
     * @Param: 
     * @Return: 
     * @Author: 杨林
     * @Date:2021/4/21 15:46
    **/
    @Override
    public void playShipOrder(Long orderId, TokenUser user, List<SeasonOrderPayDTO> payList) {

    }


    public SeasonOrder getSeasonOrderById(Long id){
        return seasonOrderMapper.selectById(id);
    }
}
